<?php

/**
 *   OPENSHOP 色卡属性相关设置
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: color_lib.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require_once(dirname(__FILE__).'/includes/init.php');
$exc = new exchange($os->table('color_lib'),$db,'img_id','img_name');

/* act操作项的初始化 */
if (empty($_REQUEST['act'])){
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}
if($_REQUEST['act']=='list'){
	
	//检查权限
	admin_priv();
	
	$smarty->assign('ur_here',      '面料色卡');  
	$smarty->assign('action_link',  array('href' => 'color_lib.php?act=add', 'text' => '添加色卡'));
	$color_lib_list = get_color_liblist();
	$smarty->assign('color_lib_list',   $color_lib_list['color_lib']);
    $smarty->assign('filter',       $color_lib_list['filter']);
    $smarty->assign('record_count', $color_lib_list['record_count']);
    $smarty->assign('page_count',   $color_lib_list['page_count']);	       
	$smarty->assign('full_page',    1);
	
    assign_query_info();
	
	$smarty->display('color_lib_list.tpl');
	
}elseif($_REQUEST['act']=='add'){
	/* 权限检查 */
    admin_priv('add_color_lib');
    
    $smarty->assign('ur_here',     '添加色卡');
	$smarty->assign('action_link',  array('href' => 'color_lib.php?act=list', 'text' => '色卡管理'));
	$smarty->assign('form_act',     'insert');
	
	assign_query_info();
	
	$guide = lattice_setting('add_color_lib');
	$guide['level_two']="color_lib_info";
	$guide['level_three']="";
	$smarty->assign('guide',$guide);
	
	$smarty->display('color_lib_info.tpl');
	
}elseif($_REQUEST['act']=='insert'){
	/* 权限检查 */
    admin_priv('add_color_lib');	

    $is_only = $exc->is_only('img_name', $_POST['img_name']);
    if (!$is_only)
    {
        sys_msg(sprintf("色卡名称 %s 已经存在！", stripslashes($_POST['img_name'])), 1);
    }	

    $is_only = $exc->is_only('img_code', $_POST['img_code']);
    if (!$is_only)
    {
        sys_msg(sprintf("色卡编号 %s 已经存在！", stripslashes($_POST['img_code'])), 1);
    }	
    $imgfile_name = '';    
    if($filesync->sync_type=='ftp'){
    	$filesync->connect();
    	$filesync->setting('color_lib', 'data/color_img', FALSE);
	    $affix_data = $filesync->put_up($_FILES['img_file']);
	    if ($affix_data !== false)
	    {
	        $imgfile_name = $affix_data['virtual_path'];
	    }
	    $filesync->quit();
    }else{
    	$imgfile_name = $filesync->upload_image($_FILES['img_file'],'color_img');
    }

    /*插入数据*/
    $sql = "INSERT INTO ".$os->table('color_lib')." VALUES (null, '$_POST[img_name]', '$_POST[img_code]', '$imgfile_name')";
    $db->query($sql);

    admin_log($_POST['img_name'],'add','color_lib');  
    
    /* 清除缓存 */
    clear_cache_files();   
    /*添加链接*/
    $link[0]['text'] = '继续添加色卡';
    $link[0]['href'] = 'color_lib.php?act=add';

    $link[1]['text'] = '返回色卡列表';
    $link[1]['href'] = 'color_lib.php?act=list';

    sys_msg('新色卡添加成功！', 0, $link);
}elseif ($_REQUEST['act']=='edit'){
	/* 权限检查 */
    admin_priv('edit_color_lib');		
    
	$sql = "SELECT img_id, img_name, img_code, img_file FROM ".$os->table('color_lib')." WHERE img_id='$_GET[img_id]' LIMIT 1";
    $color_lib = $db->GetRow($sql);
	$img_item = '<a href="'.$_CFG['pre_fetch_img'].$color_lib['img_file'].'?16,16" target="_brank">
	             <img src="'.$_CFG['pre_fetch_img'].$color_lib['img_file'].'?16,16" width="16" height="16" border="0" alt="'.
	             $color_lib['img_name'].'"/></a>';
	$color_lib['img_item'] = $img_item;
   	$smarty->assign('ur_here',     '编辑色卡记录');
    $smarty->assign('action_link', array('text' => '色卡管理', 'href' => 'color_lib.php?act=list&' . list_link_postfix()));
    $smarty->assign('color_lib',   $color_lib);
    $smarty->assign('form_act', 'update');

    assign_query_info();

	$smarty->display('color_lib_info.tpl');
	
}elseif($_REQUEST['act']=='update'){
	/* 权限检查 */
    admin_priv('edit_color_lib');	
    
    if ($_POST['img_name'] != $_POST['old_img_name']){
	    $is_only = $exc->is_only('img_name', $_POST['img_name']);
	    if (!$is_only){
	        sys_msg(sprintf('色卡名称 %s 已经存在！', stripslashes($_POST['img_name'])), 1);
	    }	
    }
    
    if ($_POST['img_code'] != $_POST['old_img_code']){
	    $is_only = $exc->is_only('img_code', $_POST['img_code']);
	    if (!$is_only){
	        sys_msg(sprintf('色卡编号 %s 已经存在！', stripslashes($_POST['img_code'])), 1);
	    }	
    }

    $imgfile_name = '';
    if($filesync->sync_type=='ftp'){
    	$filesync->connect();
    	$filesync->setting('color_lib', 'data/color_img', FALSE);
    	$filesync->set_updata(TRUE, $_POST['img_id'], 'color_lib');
	    $affix_data = $filesync->put_up($_FILES['img_file']);
	    if ($affix_data !== false)
	    {
	        $imgfile_name = $affix_data['virtual_path'];
	    }
	    $filesync->quit();
    }else{
    	$imgfile_name = $filesync->upload_image($_FILES['img_file'],'color_img');
    }
    
    $param = "img_name='$_POST[img_name]', img_code='$_POST[img_code]' ";
    if (!empty($imgfile_name)){
        //有图片上传
        $param .= " ,img_file = '$imgfile_name' ";
    }

    if ($exc->edit($param,  $_POST['img_id'])){
        /* 清除缓存 */
        clear_cache_files();
    	admin_log($_POST['img_name'],'edit','color_lib');  
        $link[0]['text'] = '返回色卡列表';
        $link[0]['href'] = 'color_lib.php?act=list&' . list_link_postfix();
        $note = vsprintf('色卡 %s 修改成功！', $_POST['img_name']);
        sys_msg($note, 0, $link);   
    }else{
        die($db->error());
    }
}elseif($_REQUEST['act']=='remove'){
	/* 权限判断 */
    check_authz_json('drop_color_lib');
	
    $img_id = intval($_GET['id']);
    
    /* 删除该色卡的图标 */
    $sql = "SELECT img_id,img_name,img_file FROM " .$os->table('color_lib'). " WHERE img_id = '$img_id'";
    $img_row = $db->getRow($sql);
 	if ($img_row['img_id']>0){
	    $rel_goods_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('goods_color'). " WHERE img_id = '$img_id'");  
	    $rel_color_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('color'). " WHERE img_id = '$img_id'");     
	    if($rel_goods_count==0 && $rel_color_count==0){	
            if($filesync->sync_type=='ftp'){
			    $filesync->connect();
			    @$filesync->drop($img_id, 'color_lib');
			    $filesync->quit();		    		
	    	}else{
		    	if (!empty($img_row['img_file'])){
			        @unlink(SOURCE_PATH . $img_row['img_file']);
			    }	    		
	    	}
		    
		    /* 删除该色卡 */
		    $exc->drop($img_id);    	
	    }else{
	    	make_json_error('"'.$img_row['img_name'] .'" 该色卡与商品、颜色等还有关联，您不能删除！');
	    } 
	}
    
    $url = 'color_lib.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
    os_header("Location: $url\n");
    exit;
    
}elseif($_REQUEST['act']=='query'){
    $color_lib_list = get_color_liblist();
	$smarty->assign('color_lib_list',   $color_lib_list['color_lib']);
    $smarty->assign('filter',       $color_lib_list['filter']);
    $smarty->assign('record_count', $color_lib_list['record_count']);
    $smarty->assign('page_count',   $color_lib_list['page_count']);	    
    make_json_result($smarty->fetch('color_lib_list.tpl'), '',
        array('filter' => $color_lib_list['filter'], 'page_count' => $color_lib_list['page_count']));	
        
}elseif($_REQUEST['act']=='drop_color_img'){
    /* 权限判断 */
    admin_priv('drop_color_lib');
    
    $img_id = intval($_GET['img_id']);
    
    $sql = "SELECT img_id,img_file FROM " .$os->table('color_lib'). " WHERE img_id = '$img_id'";
    $img_row = $db->getRow($sql);

    if ($img_row['img_id']>0){
        if($filesync->sync_type=='ftp'){
		    $filesync->connect();
		    @$filesync->drop($img_id, 'color_lib');
		    $filesync->quit();		    		
    	}else{
 		    if (!empty($img_row['img_file'])){
		        @unlink(SOURCE_PATH .$img_row['img_file']);
		    }	    		
    	}
    		    
        $sql = "UPDATE " .$os->table('color_lib'). " SET img_file = '' WHERE img_id = '$img_id'";
        $db->query($sql);
    }
    $link= array(array('text' => '重新编辑该色卡', 'href' => 'color_lib.php?act=edit&img_id=' . $img_id), array('text' => '返回列表页面', 'href' => 'color_lib.php?act=list'));
    sys_msg('删除色卡图标成功', 0, $link);
}elseif($_REQUEST['act']=='add_ext'){
	
	/* 权限检查 */
    admin_priv('add_color_lib');	
    
    $sql = "SELECT goods_id, color_id FROM " . $os->table('goods_color') . " WHERE goods_id ='$_GET[goods_id]' AND color_id='$_GET[color_id]'";
    $color_lib = $db->getRow($sql);
    $color_lib['row_indexid'] = intval($_GET['row_indexid']);
    $smarty->assign('color_lib', $color_lib);
 	$smarty->force_compile = false;
    $smarty->display('color_lib_ext_info.tpl');
}elseif ($_REQUEST['act']=='insert_ext'){
	
	/* 权限检查 */
    admin_priv('add_color_lib');	
    
    if(empty($_POST['color_id']) || empty($_POST['goods_id'])|| empty($_POST['row_indexid'])){
    	die('数据无法提交！');
    }

    $img_file = '';    
    if($filesync->sync_type=='ftp'){
    	$filesync->connect();
    	$filesync->setting('color_lib', 'data/color_img', FALSE);
	    $affix_data = $filesync->put_up($_FILES['img_file']);
	    if ($affix_data !== false)
	    {
	        $img_file = $affix_data['virtual_path'];
	    }
	    $filesync->quit();
    }else{
		$img_file = $filesync->upload_image($_FILES['img_file'],'color_img');    	
    }
    
    /*处理数据*/
	$sql = "INSERT INTO ".$os->table('color_lib')." VALUES (null, '$_POST[img_name]', '$_POST[img_code]', '$img_file')";
    $res = $db->query($sql);
    $last_img_id = $db->insert_id();
    
    if($last_img_id>0){
    	$color_lib['goods_id'] = $_POST['goods_id'];
    	$color_lib['color_id'] = $_POST['color_id'];
    	$color_lib['row_indexid'] = $_POST['row_indexid'];
    	$color_lib['last_img_id'] = $last_img_id;
    	$smarty->assign('is_insert', 'yes');
		$smarty->assign('color_lib', $color_lib);
    }
	$smarty->force_compile = false; 
    $smarty->display('color_lib_ext_info.tpl');
}
/*------------------------------------------------------ */
//-- 搜索色卡
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_color_lib_list'){
	
	check_authz_json('edit_goods_color');
	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;
    $filter = $json->decode($_GET['JSON']);

    $where = " WHERE 1 ";
  	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ? " AND (img_name LIKE '%" . mysql_like_quote($filter->keyword)."%') OR (img_code LIKE '%" . mysql_like_quote($filter->keyword) . "%')" : '';
    $sql = 'SELECT * FROM ' . $os->table('color_lib') . $where . ' ORDER BY img_id DESC LIMIT 50';
    $res = $db->query($sql);
    $opt = array();
    while ($row = $db->fetchRow($res)){
    	$img_item = '';
    	if(!empty($row['img_file']))
        	$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$row['img_name'].'"/>';
        $opt[]  = array('value' => $row['img_id'], 'text' => $row['img_name'], 'code'=>$row['img_code'], 'img_item'=>$img_item);
    }
    make_json_result($opt);
}elseif($_REQUEST['act']=='up_goods_color_lib'){
	
	check_authz_json('edit_goods_color');
	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;
    $filter = $json->decode($_GET['JSON']);
    
    $sql = "UPDATE " . $os->table('goods_color') . " SET img_id='$filter->img_id' WHERE goods_id='$filter->goods_id' AND color_id='$filter->color_id'";
    $res = $db->query($sql); 
    $row = $db->getRow("SELECT cl.* FROM " . $os->table('goods_color') . " gc LEFT JOIN " . 
                            $os->table('color_lib') . " cl ON gc.img_id=cl.img_id WHERE " . 
                            " gc.goods_id='$filter->goods_id' AND gc.color_id='$filter->color_id'");
    
    $row['img_item'] = '';
    if(!empty($row['img_file']))
         $row['img_item'] = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$row['img_name'].'"/>';
    $opt = array_merge(array('row_indexid'=>$filter->row_indexid , 'mes'=>'successful'),array_slice($row,1));
    make_json_result($opt);			
}

function color_option_list(){
	static $res = NULL;
	if ($res === NULL){
		$sql = "SELECT color_id,color_name from ". $GLOBALS['os']->table('color') ." order by color_id desc";
		$res = $GLOBALS['db']->getAll($sql);
	}
	$color_list = array();
    foreach ($res AS $row)
    {
        $color_list[$row['color_id']] = $row['color_name'];
    }		
    return $color_list;	
}

function get_color_liblist(){
	global $_CFG;

    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array();

 		$filter['keyword']  = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
 		
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }        
        
        if ($filter['keyword'])
        {
			$where .= " AND (img_code LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR img_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }        
        
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('color_lib').' where 1 '.$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 查询记录 */
		$sql = "SELECT img_id, img_name, img_code, img_file FROM ". $GLOBALS['os']->table('color_lib').' where 1 '.$where." ORDER BY img_id DESC";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);
    
    $arr = array();
    $img_item = '';
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $img_item = '<a href="'.$_CFG['pre_fetch_img'].$rows['img_file'].'?16,16" target="_brank">
                     <img src="'.$_CFG['pre_fetch_img'].$rows['img_file'].'?16,16" width="16" height="16" border="0" 	alt="'.$rows['img_name'].'"/>
                     </a>';
        $rows['img_item'] = $img_item;

        $arr[] = $rows;
    }	
    
    return array('color_lib' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}
?>